<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

define("EMPTY", " - ");
class Dashboard extends CI_Controller {

	//Doctrine EntityManager
	public $em;

	function __construct() {
		parent::__construct();

		//Not required if you autoload the library
		$this -> load -> library('doctrine');

		//Instantiate a Doctrine Entity Manager
		$this -> em = $this -> doctrine -> em;
		// $conn = $this->em->getConnection();
		//var_dump(models\service\CurrentUser::user());
		if (models\service\CurrentUser::user() == FALSE){
			header('location: ' . base_url());
		}

		// $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'varchar');
	}
	
	
	// START Katalog
	public function index() {
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$arr = array("ENTRY1" , "ENTRY2");
		if (isPermitt($userProfiles, $arr) === FALSE){
			die("CANNOT ACCESS");
		}
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url() . "dashboard"),
								 array("label" => "Report", "link" => NULL)
								);
								
		$serv = new models\service\BerkasService;
					   
		// default search bar state
		$searchBar['fieldnames'] = array( array('label' => 'Nama Perpustakaan',
												'value' => 'Berkas.Perpustakaan.nama'
												),
										  array('label' => 'Nama Indikator',
												'value' => 'Berkas.Indicator.nama'
												)		
										);								
		$pFieldName[0] = "Berkas.Perpustakaan.nama";
		$pFieldValue[0] = "";
		$pCondition[0] = "LIKE";
		$searchBy = FALSE;
		// end default search bar state										
		if ($this->input->post('searchPar') != NULL){			
			$pFieldName=$this->input->post('fieldName');
			$pFieldValue=$this->input->post('fieldValue');
			$pCondition=$this->input->post('condition');
			
			if ($pFieldValue[0] != NULL){
				$searchBy = TRUE;
			}
		}
		
		$searchBar['pFieldName'] = $pFieldName;
		$searchBar['pCondition'] = $pCondition;
		$searchBar['pFieldValue'] = $pFieldValue;
		$data['searchBar'] = $searchBar;
		
		// default paging bar state
		$indexAndCount[0] = 1;
		$indexAndCount[1] = 5;
		$orders = array(
						array('fieldName' => 'Berkas.updateDate', 'orderType' => 'DESC')
					   );
		   
		if ($this->input->post('activePage') != NULL){
			$indexAndCount[0] = $this->input->post('activePage');			
		}
		
		if ($this->input->post('activePageBar') != NULL){
			$indexAndCount[0] = $this->input->post('activePageBar');
		} 
		// end default paging bar state
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
	//	$criteria = array('profile' => $userProfiles[0]->getProfile());
	//	$ps = $this->em->getRepository('\models\entities\ProcedureStep')->findBy($criteria);
/*		echo "<pre>"; print_r($userProfiles);die();
		echo "<pre>"; print_r($ps);die(); */
		if ($searchBy === TRUE){
			$i = count($searchBar['pFieldName']);
			$searchBar['pFieldName'][$i] = "Inbox.procedureStep";
			$searchBar['pCondition'][$i] = "EQUAL";
			$searchBar['pFieldValue'][$i] = $ps[0]->getId();
			
			if ($ps[0]->getId() == 1){
				$searchBar['pFieldName'][$i+1] = "Berkas.reporter";
				$searchBar['pCondition'][$i+1] = "EQUAL";
				$searchBar['pFieldValue'][$i+1] = $user->getUserId();
			}
			
			$data['pBerkas'] = $serv->paginateBerkasByMap($searchBar, $indexAndCount, $orders);
		} else {			
			$searchBar['pFieldName'][0] = "Inbox.procedureStep.id";
			$searchBar['pCondition'][0] = "IN";
			$searchBar['pFieldValue'][0] = "1,2";
			
			$searchBar['pFieldName'][1] = "Berkas.reporter";
			$searchBar['pCondition'][1] = "EQUAL";
			$searchBar['pFieldValue'][1] = $user->getUserId();
						 			
			$data['pBerkas'] = $serv->paginateBerkasByMap($searchBar, $indexAndCount, $orders);	
		}		
		$data['userProfiles'] = $userProfiles;
		$this -> load -> view('berkas/index', $data);		
	}

	public function indexVer() {
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		//echo "<pre>";print_r($userProfiles[0]->getProfile()->getNamaProfile());die();
		$arr = array("VERIFIER1" , "VERIFIER1_2","VERIFIER2");
		if (isPermitt($userProfiles, $arr) === FALSE){
			die("CANNOT ACCESS");
		}
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url() . "dashboard/indexVer"),
								 array("label" => "Report", "link" => NULL)
								);
								
		$serv = new models\service\BerkasService;
					   
		// default search bar state
		$searchBar['fieldnames'] = array( array('label' => 'Nama Perpustakaan',
												'value' => 'Berkas.Perpustakaan.nama'
												),
										  array('label' => 'Nama Indikator',
												'value' => 'Berkas.Indicator.nama'
												)		
										);								
		$pFieldName[0] = "Berkas.Perpustakaan.nama";
		$pFieldValue[0] = "";
		$pCondition[0] = "LIKE";
		$searchBy = FALSE;
		// end default search bar state										
		if ($this->input->post('searchPar') != NULL){			
			$pFieldName=$this->input->post('fieldName');
			$pFieldValue=$this->input->post('fieldValue');
			$pCondition=$this->input->post('condition');
			
			if ($pFieldValue[0] != NULL){
				$searchBy = TRUE;
			}
		}
		
		$searchBar['pFieldName'] = $pFieldName;
		$searchBar['pCondition'] = $pCondition;
		$searchBar['pFieldValue'] = $pFieldValue;
		$data['searchBar'] = $searchBar;
		
		// default paging bar state
		$indexAndCount[0] = 1;
		$indexAndCount[1] = 5;
		$orders = array(
						array('fieldName' => 'Berkas.updateDate', 'orderType' => 'DESC')
					   );
		   
		if ($this->input->post('activePage') != NULL){
			$indexAndCount[0] = $this->input->post('activePage');			
		}
		
		if ($this->input->post('activePageBar') != NULL){
			$indexAndCount[0] = $this->input->post('activePageBar');
		} 
		// end default paging bar state
		
		//$criteria = array('profile' => $userProfiles[0]->getProfile());
		$ps = $this->em->getRepository('\models\entities\ProcedureStep')->findByUserProfiles($userProfiles, array(7,8,11));
		foreach ($ps as  $row){
			$arrPs[] = $row->getId();
		}
		if ($searchBy === TRUE){
			$i = count($searchBar['pFieldName']);
			$searchBar['pFieldName'][$i] = "Inbox.procedureStep";
			$searchBar['pCondition'][$i] = "EQUAL";
			$searchBar['pFieldValue'][$i] = $ps[0]->getId();
			
			if ($ps[0]->getId() == 1){
				$searchBar['pFieldName'][$i+1] = "Berkas.reporter";
				$searchBar['pCondition'][$i+1] = "EQUAL";
				$searchBar['pFieldValue'][$i+1] = $user->getUserId();
			}
			
			$data['pBerkas'] = $serv->paginateBerkasByMap($searchBar, $indexAndCount, $orders);
		} else {
						
			$searchBar['pFieldName'][0] = "Inbox.procedureStep.id";
			$searchBar['pCondition'][0] = "IN";
			$searchBar['pFieldValue'][0] = implode(",",$arrPs);
					 			
			$data['pBerkas'] = $serv->paginateBerkasByMap($searchBar, $indexAndCount, $orders);	
		}		
		$data['userProfiles'] = $userProfiles;
		
		$criteria = array('userId' => $user);
		$data['userVerifikator'] = $this->em->getRepository('\models\entities\UserVerifikator')->findBy($criteria);
		$data['user'] = $user;
		$this -> load -> view('berkas/indexVer', $data);		
	}

	public function indexApp() {
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		if (isPermitt($userProfiles, "APPROVER") === FALSE){
			die("CANNOT ACCESS");
		}
		
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url() . "dashboard/indexApp"),
								 array("label" => "Report", "link" => NULL)
								);
								
		$serv = new models\service\BerkasService;
					   
		// default search bar state
		$searchBar['fieldnames'] = array( array('label' => 'Nama Perpustakaan',
												'value' => 'Berkas.Perpustakaan.nama'
												),
										  array('label' => 'Nama Indikator',
												'value' => 'Berkas.Indicator.nama'
												)		
										);								
		$pFieldName[0] = "Berkas.Perpustakaan.nama";
		$pFieldValue[0] = "";
		$pCondition[0] = "LIKE";
		$searchBy = FALSE;
		// end default search bar state										
		if ($this->input->post('searchPar') != NULL){			
			$pFieldName=$this->input->post('fieldName');
			$pFieldValue=$this->input->post('fieldValue');
			$pCondition=$this->input->post('condition');
			
			if ($pFieldValue[0] != NULL){
				$searchBy = TRUE;
			}
		}
		
		$searchBar['pFieldName'] = $pFieldName;
		$searchBar['pCondition'] = $pCondition;
		$searchBar['pFieldValue'] = $pFieldValue;
		$data['searchBar'] = $searchBar;
		
		// default paging bar state
		$indexAndCount[0] = 1;
		$indexAndCount[1] = 5;
		$orders = array(
						array('fieldName' => 'Berkas.updateDate', 'orderType' => 'DESC')
					   );
		   
		if ($this->input->post('activePage') != NULL){
			$indexAndCount[0] = $this->input->post('activePage');			
		}
		
		if ($this->input->post('activePageBar') != NULL){
			$indexAndCount[0] = $this->input->post('activePageBar');
		} 
		// end default paging bar state
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$criteria = array('profile' => $userProfiles[0]->getProfile());
		$ps = $this->em->getRepository('\models\entities\ProcedureStep')->findBy($criteria);
		//echo "<pre>";print_r($ps);
		// echo $ps[0]->getId();
		// die();
		if ($searchBy === TRUE){
			$i = count($searchBar['pFieldName']);
			$searchBar['pFieldName'][$i] = "Inbox.procedureStep";
			$searchBar['pCondition'][$i] = "EQUAL";
			$searchBar['pFieldValue'][$i] = $ps[0]->getId();
			
			if ($ps[0]->getId() == 1){
				$searchBar['pFieldName'][$i+1] = "Berkas.reporter";
				$searchBar['pCondition'][$i+1] = "EQUAL";
				$searchBar['pFieldValue'][$i+1] = $user->getUserId();
			}
			
			$data['pBerkas'] = $serv->paginateBerkasByMap($searchBar, $indexAndCount, $orders);
		} else {			
			$searchBar['pFieldName'][0] = "Inbox.procedureStep";
			$searchBar['pCondition'][0] = "EQUAL";
			$searchBar['pFieldValue'][0] = $ps[0]->getId();
			if ($ps[0]->getId() == 1){
				$searchBar['pFieldName'][1] = "Berkas.reporter";
				$searchBar['pCondition'][1] = "EQUAL";
				$searchBar['pFieldValue'][1] = $user->getUserId();
			}			 			
			$data['pBerkas'] = $serv->paginateBerkasByMap($searchBar, $indexAndCount, $orders);	
		}		
		$data['user'] = $user;
		$data['userProfiles'] = $userProfiles;
		$this -> load -> view('berkas/indexApp', $data);		
	}
	
	public function createEditReport($id="0"){
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url() . "dashboard.php"),
								     array("label" => "Report", "link" => base_url() . "dashboard"),
									 array("label" => "Edit / Create New Report", "link" => NULL)
								);
								
		$data['id'] = $id;
		$serv = new models\service\BerkasService;
		if ($id != "0"){
			// init the data
			$berkas = $serv->getBerkasById(TRUE, $id);
			$berkasComment = NULL;
			$berkasTraining = $this -> em -> getRepository('\models\entities\BerkasTraining') -> findOneBy(array('id' => $berkas));
			$memberOfTraining = $this -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy(array('berkas' => $berkas));
			$berkasComments = $this -> em -> getRepository('\models\entities\BerkasComment') -> findBy(array('berkas' => $berkas), array('createdDate' => 'ASC'));									
			$berkasAttachments = $this -> em -> getRepository('\models\entities\BerkasAttachment') -> findBy(array('berkas' => $berkas), array('createdDate' => 'ASC'));
		} else {
			$berkas = NULL;
			$berkasComments = NULL;
			$berkasTraining = NULL;
			$memberOfTraining = NULL;
			$berkasAttachments = NULL;			
		}
		//echo "<pre>";print_r($berkas->getInbox()->getProcedureStep()->getId());die(); 
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['userProfiles'] = $userProfiles;
		$data['berkasAttachments'] = $berkasAttachments;
		$data['memberOfTraining'] = $memberOfTraining;
		//$jenisProsedures = $this -> em -> getRepository('\models\entities\JenisProsedur') -> findByUserProfiles($userProfiles); 
		$data['jenisTrainingList'] = $this -> em -> getRepository('\models\entities\JenisTraining') -> findByUserProfiles($userProfiles);
		//$data['tipeBerkasList'] = $serv->findAllTipeBerkas(array('nama' => 'asc'));
		$data['tipeBerkasList'] = $this -> em -> getRepository('\models\entities\TipeBerkas') -> findBy(array('status'=> 1));
		$data['perpusList'] = $serv->findAllPerpustakaan(array('nama' => 'asc'));
		$data['desaList'] = $serv->findAllDesa(array('nama' => 'asc'));
		$data['berkas'] = $berkas;
		$data['berkasTraining'] = $berkasTraining;
		$data['berkasComments'] = $berkasComments;
		
		$this->load->view('berkas/createEdit', $data);
	}

	public function createEditVer($id="0"){
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url() . "dashboard.php"),
								     array("label" => "Report", "link" => base_url() . "dashboard"),
									 array("label" => "Edit / Create New Report", "link" => NULL)
								);
								
		$data['id'] = $id;
		$serv = new models\service\BerkasService;
		if ($id != "0"){
			// init the data
			$berkas = $serv->getBerkasById(TRUE, $id);
			$berkasComment = NULL;
			$berkasTraining = $this -> em -> getRepository('\models\entities\BerkasTraining') -> findOneBy(array('id' => $berkas));
			$memberOfTraining = $this -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy(array('berkas' => $berkas));
		// 	echo "<pre>";print_r($memberOfTraining);die();
			$berkasAttachments = $this -> em -> getRepository('\models\entities\BerkasAttachment') -> findBy(array('berkas' => $berkas), array('createdDate' => 'ASC'));
			$berkasComments = $this -> em -> getRepository('\models\entities\BerkasComment') -> findBy(array('berkas' => $berkas), array('createdDate' => 'ASC'));									
		} else {
			$berkas = NULL;
			$berkasComments = NULL;
			$berkasTraining = NULL;
			$memberOfTraining = NULL;
			$berkasAttachments = NULL;
		}
		
		$isReadOnly = "readonly";
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['berkasAttachments'] = $berkasAttachments;
		$data['userProfiles'] = $userProfiles;
		$data['memberOfTraining'] = $memberOfTraining;
		$data['jenisTrainingList'] = $this -> em -> getRepository('\models\entities\JenisTraining') -> findAll();
		$data['tipeBerkasList'] = $serv->findAllTipeBerkas(array('nama' => 'asc'));
		$data['perpusList'] = $serv->findAllPerpustakaan(array('nama' => 'asc'));
		$data['distrikList'] = $serv->findAllDistrik(array('nama' => 'asc'));
		$data['berkas'] = $berkas;
		$data['berkasTraining'] = $berkasTraining;
		$data['isReadOnly'] = $isReadOnly;
		$data['berkasComments'] = $berkasComments;
		
		$criteria = array('userId' => $user);
		$data['userVerifikator'] = $this->em->getRepository('\models\entities\UserVerifikator')->findBy($criteria);
		
		$this->load->view('berkas/createEditVer', $data);
	}

	public function createEditApp($id="0"){
		$data['breadcrumb'] = array( array("label" => "Home", "link" => base_url() . "dashboard.php"),
								     array("label" => "Report", "link" => base_url() . "dashboard"),
									 array("label" => "Edit / Create New Report", "link" => NULL)
								);
								
		$data['id'] = $id;
		$serv = new models\service\BerkasService;
		if ($id != "0"){
			// init the data
			$berkas = $serv->getBerkasById(TRUE, $id);
			$berkasTraining = $this -> em -> getRepository('\models\entities\BerkasTraining') -> findOneBy(array('id' => $berkas));
			$memberOfTraining = $this -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy(array('berkas' => $berkas));
			$berkasComments = $this -> em -> getRepository('\models\entities\BerkasComment') -> findBy(array('berkas' => $berkas), array('createdDate' => 'ASC'));								
		} else {
			$berkas = NULL;
			$berkasComments = NULL;
			$berkasTraining = NULL;
			$memberOfTraining = NULL;
		}
		
		$isReadOnly = "readonly";
		$user = models\service\CurrentUser::user();
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		$data['userProfiles'] = $userProfiles;
		$data['memberOfTraining'] = $memberOfTraining;
		$data['jenisTrainingList'] = $this -> em -> getRepository('\models\entities\JenisTraining') -> findAll();
		$data['tipeBerkasList'] = $serv->findAllTipeBerkas(array('nama' => 'asc'));
		$data['perpusList'] = $serv->findAllPerpustakaan(array('nama' => 'asc'));
		$data['distrikList'] = $serv->findAllDistrik(array('nama' => 'asc'));
		$data['berkas'] = $berkas;
		$data['berkasTraining'] = $berkasTraining;
		$data['isReadOnly'] = $isReadOnly;
		$data['berkasComments'] = $berkasComments;
		
		$isSpesialFlowBerkasTraining = FALSE;
		$isUserHasSubmit = FALSE;
		if ($berkas->getTipe()->getId() == "TRAINING"){
			$criteria = array("id" => $berkas);	
			$berkasTraining = $this -> em -> getRepository('\models\entities\BerkasTraining')->findOneBy($criteria);
			$tipeBerkas = $berkas->getTipe()->getNama(). " - " . $berkasTraining->getJenisTraining()->getNama();	
			if ($berkasTraining->getJenisTraining()->getJenisFlow() == 2){
				$isSpesialFlowBerkasTraining = TRUE;
				$criteria = array("id" => $berkas);	
				$inbox = $this -> em -> getRepository('\models\entities\Inbox')->findOneBy($criteria);
				if ($inbox->getLastApp() == $user->getUserId()){
					$isUserHasSubmit = TRUE;
				}			
			}
		}
		
		$data['isUserHasSubmit'] = $isUserHasSubmit;
		$this->load->view('berkas/createEditApp', $data);
	}
	
	public function saveReport(){
		//echo "<pre>";print_r($_FILES);die('tes');	
		if ($this -> input -> post('Berkas_id') != NULL) {
			$objects = array('Berkas');
			$except['Berkas'] = array('reporter','verifier','approver','comments', 'startDate','endDate','result','updateDate');
			$xfields = NULL;
			$jmlPria = 0; $jmlWanita = 0; $jmlStaff=0; $jmlNonStaff=0;
			if ($this->input->post('Berkas_tipe') == 'TRAINING'){
				array_push($objects, 'BerkasTraining');
				$except['BerkasTraining'] = array();
				if ($this->input->post('participantName') != NULL){
					$participantNames = $this->input->post('participantName');
					$participantGenders = $this->input->post('participantGender');
					$participantStaffs = $this->input->post('participantStaff');
					$i=0;					
					foreach ($participantNames as $participantName){
						$xfields['MemberOfTraining'][$i]['name'] = $participantName;
						$xfields['MemberOfTraining'][$i]['gender'] = $participantGenders[$i];
						$xfields['MemberOfTraining'][$i]['staff'] = $participantStaffs[$i];
						$i++;
					}
					
					foreach ($xfields['MemberOfTraining'] as $row){
						if ($row['gender'] == "M"){
							$jmlPria++;
						} else {
							$jmlWanita++;
						}
						
						if ($row['staff'] == "S"){
							$jmlStaff++;
						} else {
							$jmlNonStaff++;
						}
					}
				}				
			}
			
			$fields = collectingHtmlInput($objects, $except);
			if ($fields != NULL){
				array_push($fields, $xfields);				
			}
			//echo "<pre>";print_r($fields);//die();
			$serv = new models\service\BerkasService;
			
			// HARDCODE!! 			
			$user = models\service\CurrentUser::user();			
			$criteria = array('userId' => $user->getUserId());
			$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findOneBy($criteria);
			
			$fields['Profile']['id'] = 6;
			$fields['Berkas']['reporter'] = $user->getUserId();
			if ($this->input->post('Berkas_tipe') == 'TRAINING'){
				$fields['BerkasTraining']['jmlStaff'] = $jmlStaff;
				$fields['BerkasTraining']['jmlNonStaff'] = $jmlNonStaff;
				$fields['BerkasTraining']['jmlPria'] = $jmlPria;
				$fields['BerkasTraining']['jmlWanita'] = $jmlWanita;
			}
			//echo "<pre>"; print_r($fields);die();
			//$res = $serv->saveBerkasAsDraft($fields);
			//var_dump($res);die();
			if ($serv->saveBerkasAsDraft($fields) !== FALSE){				
				header('location: ' . base_url() . 'dashboard');	
			} else {
				die('NOT FOUND');
			}			
		} else {
			echo "<pre>";print_r($_POST);
			echo "<pre>";print_r($_FILES);
			die('no parameter');
		}
	}
	
	public function saveAndSubmitReport(){
		//echo "<pre>"; print_r($_POST);die();
		if ($this -> input -> post('Berkas_id') != NULL) {
			$objects = array('Berkas');
			$except['Berkas'] = array('reporter','verifier','approver','comments', 'startDate','endDate','result','updateDate');
			$xfields = NULL;
			$jmlPria = 0; $jmlWanita = 0; $jmlStaff=0; $jmlNonStaff=0;
			if ($this->input->post('Berkas_tipe') == 'TRAINING'){
				array_push($objects, 'BerkasTraining');
				$except['BerkasTraining'] = array();
				if ($this->input->post('participantName') != NULL){
					$participantNames = $this->input->post('participantName');
					$participantGenders = $this->input->post('participantGender');
					$participantStaffs = $this->input->post('participantStaff');
					$i=0;					
					foreach ($participantNames as $participantName){
						$xfields['MemberOfTraining'][$i]['name'] = $participantName;
						$xfields['MemberOfTraining'][$i]['gender'] = $participantGenders[$i];
						$xfields['MemberOfTraining'][$i]['staff'] = $participantStaffs[$i];
						$i++;
					}
					
					foreach ($xfields['MemberOfTraining'] as $row){
						if ($row['gender'] == "M"){
							$jmlPria++;
						} else {
							$jmlWanita++;
						}
						
						if ($row['staff'] == "S"){
							$jmlStaff++;
						} else {
							$jmlNonStaff++;
						}
					}
				}				
			}
			
			$fields = collectingHtmlInput($objects, $except);
			if ($fields != NULL){
				array_push($fields, $xfields);				
			}
			//echo "<pre>";print_r($fields);//die();
			$serv = new models\service\BerkasService;
			
			// HARDCODE!! 			
			$user = models\service\CurrentUser::user();			
			$criteria = array('userId' => $user->getUserId());
			$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findOneBy($criteria);
			
			$fields['Profile']['id'] = 6;
			$fields['Berkas']['reporter'] = $user->getUserId();
			if ($this->input->post('Berkas_tipe') == 'TRAINING'){
				$fields['BerkasTraining']['jmlStaff'] = $jmlStaff;
				$fields['BerkasTraining']['jmlNonStaff'] = $jmlNonStaff;
				$fields['BerkasTraining']['jmlPria'] = $jmlPria;
				$fields['BerkasTraining']['jmlWanita'] = $jmlWanita;
			}
			
			if ($serv->saveAndSubmitBerkas($fields) !== FALSE){				
				header('location: ' . base_url() . 'dashboard');	
			}			
		}
	}
	
	public function submitReportVer(){
		$id = $this->input->post('Berkas_id');
		//var_dump($id);
		echo "<pre>"; print_r($_POST);die();
		if ($id != "0"){
			$criteria = array('id' => $id);
			$berkas = $this->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
			$serv = new models\service\BerkasService;
			$user = models\service\CurrentUser::user();			
			$profileId = $this->input->post('Profile_id');
			if ($profileId == "7"){
				$berkas->setVerifier($user->getUserId());	
			} else if ($profileId == "8"){
				$berkas->setApprover($user->getUserId());
				$berkas->setEndDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
				$berkas->setResult("OK");
			}			
			  
			$criteria = array('id' => $berkas);
			$isSpesialFlowBerkasTraining = FALSE;
			if ($berkas->getTipe()->getId() == "TRAINING"){
				$berkasTraining = $this->em->getRepository('\models\entities\BerkasTraining')->findOneBy($criteria);
				if ($berkasTraining->getJenisTraining()->getJenisFlow() == 2){
					$isSpesialFlowBerkasTraining = TRUE;	
				}	
			} 			  
			
			if ($isSpesialFlowBerkasTraining){
				$criteria = array('userId' => $user);
				$userVerifikator = $this->em->getRepository('\models\entities\UserVerifikator')->findBy($criteria);
				
				$criteria = array('id' => $berkas);
				$inbox = $this->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				if ($userVerifikator[0]->getJenisVerifikator()->getId()==2 && $inbox->getJumlahVerify() == 1){
					if ($serv->submitBerkasForVerAndApp($berkas, $profileId, "OK") !== FALSE){
						header('location: ' . base_url() . 'dashboard/indexVer');
					}	
				} else {					
					if ($serv->submitReview($berkas, $profileId, "OK") !== FALSE){
						header('location: ' . base_url() . 'dashboard/indexVer');
					}					
				}
								
			} else {			
				if ($serv->submitBerkasForVerAndApp($berkas, $profileId, "OK") !== FALSE){
					if ($profileId=="6"){
						header('location: ' . base_url() . 'dashboard');	
					} else if ($profileId == "7"){
						header('location: ' . base_url() . 'dashboard/indexVer');
					} else if ($profileId == "8"){
						header('location: ' . base_url() . 'dashboard/indexApp');
					}					
				}	
			}
							
		} else {
			die("NOT FOUND");
		}		
	}

	public function submitReportApp(){
		$id = $this->input->post('Berkas_id');
		
		if ($id != "0"){
			$criteria = array('id' => $id);
			$berkas = $this->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
			$serv = new models\service\BerkasService;
			$user = models\service\CurrentUser::user();			
			$profileId = $this->input->post('Profile_id');
			if ($profileId == "7"){
				$berkas->setVerifier($user->getUserId());	
			} else if ($profileId == "8"){
				$berkas->setApprover($user->getUserId());
				$berkas->setEndDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
				$berkas->setResult("OK");
			}			
			  
			$isSpesialFlowBerkasTraining = FALSE; 
			if ($berkas->getTipe()->getId()=="TRAINING"){
				$criteria = array('id' => $berkas);
				$berkasTraining = $this->em->getRepository('\models\entities\BerkasTraining')->findOneBy($criteria);
				if ($berkasTraining->getJenisTraining()->getJenisFlow() == 2){
					$isSpesialFlowBerkasTraining = TRUE;	
				}	
			}
			  
			if ($isSpesialFlowBerkasTraining){
				$criteria = array('id' => $berkas);
				$inbox = $this->em->getRepository('\models\entities\Inbox')->findOneBy($criteria);
				if ($inbox->getJumlahApprover() == 1){
					if ($serv->submitBerkasForVerAndApp($berkas, $profileId, "FINISH") !== FALSE){
						header('location: ' . base_url() . 'dashboard/indexApp');
					}	
				} else {					
					if ($serv->submitFirstApprove($berkas, $profileId, "OK") !== FALSE){
						header('location: ' . base_url() . 'dashboard/indexApp');
					}					
				}								
			} else {			
				if ($serv->submitBerkasForVerAndApp($berkas, $profileId, "FINISH") !== FALSE){
					if ($profileId=="6"){
						header('location: ' . base_url() . 'dashboard');	
					} else if ($profileId == "7"){
						header('location: ' . base_url() . 'dashboard/indexVer');
					} else if ($profileId == "8"){
						header('location: ' . base_url() . 'dashboard/indexApp');
					}					
				}	
			}
							
		} else {
			die("NOT FOUND");
		}		
	}

	public function submitReport(){
		$id = $this->input->post('id');
		if ($id != "0"){
			$criteria = array('id' => $id);
			$berkas = $this->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
			$serv = new models\service\BerkasService;
			echo "<pre>";print_r($_POST);
			$profileId = $this->input->post('Profile_id');
			// $res = $serv->submitBerkas($berkas, $profileId);
			// var_dump($res);die();
			if ($serv->submitBerkas($berkas, $profileId) !== FALSE){
				if ($profileId=="6"){
					header('location: ' . base_url() . 'dashboard');	
				} else if ($profileId == "7"){
					header('location: ' . base_url() . 'dashboard/indexVer');
				} else if ($profileId == "8"){
					header('location: ' . base_url() . 'dashboard/indexApp');
				}								
			}				
		} else {
			die("NOT FOUND");
		}
		
	}
	
	public function returnReport(){
		$id = $this->input->post('id');
		
		if ($id != "0"){
			$criteria = array('id' => $id);
			
			$berkas = $this->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
			$serv = new models\service\BerkasService;
			$user = models\service\CurrentUser::user();			
			$profileId = $this->input->post('Profile_id');
			if ($profileId == "7"){
				$berkas->setVerifier($user->getUserId());	
			} else if ($profileId == "8"){
				$berkas->setApprover($user->getUserId());				
			}			
			  
			if ($serv->submitBerkasForVerAndApp($berkas, $profileId,'NOK') !== FALSE){
				if ($profileId=="6"){
					header('location: ' . base_url() . 'dashboard');	
				} else if ($profileId == "7"){
					header('location: ' . base_url() . 'dashboard/indexVer');
				} else if ($profileId == "8"){
					header('location: ' . base_url() . 'dashboard/indexApp');
				}					
			}				
		} else {
			die("NOT FOUND");
		}
		
	}
	
	public function cancelReport($profileId="0", $id = "0"){
		//$id = $this->input->post('Berkas_id');
		
		if ($id != "0"){
			$criteria = array('id' => $id);
			$berkas = $this->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
			$serv = new models\service\BerkasService;
			$user = models\service\CurrentUser::user();			
			  
			if ($serv->submitBerkasForVerAndApp($berkas, $profileId,'CANCEL') !== FALSE){
				if ($profileId=="6"){
					header('location: ' . base_url() . 'dashboard');	
				} else if ($profileId == "7"){
					header('location: ' . base_url() . 'dashboard/indexVer');
				} else if ($profileId == "8"){
					header('location: ' . base_url() . 'dashboard/indexApp');
				}					
			}				
		} else {
			die("NOT FOUND");
		}
	}
	
	public function returnReportPost(){
		//echo "<pre>";print_r($_POST);die();
		$id = $this->input->post('Berkas_id');		
		if ($id != "0"){
			$criteria = array('id' => $id);
			$berkas = $this->em->getRepository('\models\entities\Berkas')->findOneBy($criteria);
			$serv = new models\service\BerkasService;
			$user = models\service\CurrentUser::user();			
			$profileId = $this->input->post('Profile_id');
			if ($profileId == "7"){
				$berkas->setVerifier($user->getUserId());	
			} else if ($profileId == "8"){
				$berkas->setApprover($user->getUserId());				
			}			
			  
			if ($serv->submitBerkasForVerAndApp($berkas, $profileId,'NOK') !== FALSE){
				if ($profileId=="6"){
					header('location: ' . base_url() . 'dashboard');	
				} else if ($profileId == "7"){
					header('location: ' . base_url() . 'dashboard/indexVer');
				} else if ($profileId == "8"){
					header('location: ' . base_url() . 'dashboard/indexApp');
				}					
			}				
		} else {
			die("NOT FOUND");
		}
		
	}
	
	public function viewBerkasAttachment($attachId){
	/*
		$permission = $this->getPermission();
		
		if (!in_array("001", $permission)){
			header('location: ' . base_url() . 'home'); 
		}*/
		$criteria = array('id' => $attachId);
		$attach = $this -> em -> getRepository('\models\entities\BerkasAttachment') -> findOneBy($criteria);
		
		// echo "<pre>"; print_r($_SERVER);die();
		$file_location = $attach->getPath(); // store as constant maybe inside index.php - PDF = 'uploads/pdf/';
		// die($file_location); 
	             //must have PDF viewer installed in browser !
	    $content = file_get_contents($file_location);
	    
		/*if ($berkas->getTypeFile() == "application/pdf"){
			
		}*/
		if ($attach->getTypeFile() == "application/pdf"){
			$this->output
	           ->set_content_type('application/pdf')
	           ->set_output($content, $attach->getBerkas()->getId().'.pdf');	
		} else if ($attach->getTypeFile() == "application/xls") {
			$this->output
	           ->set_content_type('application/xls')
	           ->set_output($content, $attach->getBerkas()->getId().'.xls');	
		} else {
			$this->output
	           ->set_content_type($attach->getTypeFile());
		}
	    
	}
}

